//
//  ClubGamesCommitViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/19.
//

import UIKit
import ZLPhotoBrowser
import Photos
import Cosmos

class ClubGamesCommitViewController: ClubBaseViewController {

    private let scrollView = UIScrollView()
    private let containerView = UIView()
    private let closeButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let gameImageV = c_make_ex(UIImageView.self)
        .corner(4.0.Scale).mode(.scaleAspectFill).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .font(16.font_semiBold).color(.black).end()
    private let sendButton = c_make_ex(UIButton.self)
        .image("Square_pushEnable").image("Square_pushDisable", state: .disabled).end()
    private let placeholderLabel = c_make_ex(UILabel.self)
        .text("关于这款游戏，大家都想听听你的看法捏~（不少于8个字符）")
        .font(15.font_medium).color("#AEB0B3").line(0).end()
    private let scoreLabel = c_make_ex(UILabel.self)
        .font(14.font_medium).color("#2E3033").text("评分").end()
    private let scoreSubLabel = c_make_ex(UILabel.self)
        .font(12.font_medium).color("#A0A3AA")
        .text("点击星星评分").end()
    private let lineView = c_make_ex(UIView.self)
        .bgColor("#F2F3F5").end()
    private var starView = CosmosView()
    // 创建UITextView
    private let textView: UITextView = {
        let tv = UITextView()
        tv.font = 15.font_medium
        tv.textColor = "#47494D".toColor
        tv.tintColor = "#47494D".toColor
        tv.isScrollEnabled = false  // 禁止滚动
        tv.backgroundColor = .clear
        tv.translatesAutoresizingMaskIntoConstraints = false
        return tv
    }()
    private let functionView = ClubDynamicFunctionView()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private var picImageView = ClubGamesCommitMediaView()
    
    var gameModels: [ClubDynamicGameModel]?
    var topicModels: [ClubDynamicGameModel]?
    
    var updateDataBlock: (() -> Void)?
    
    private var images: [UIImage] = []
    private var assets: [PHAsset] = []
    private var imageUrlArr = [String]()
    var point = 0
    var gameId: String = ""
    
    init() {
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .fullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var topModel: ClubGameDetailModel?{
        didSet{
            guard let md = topModel else { return }
            
            self.titleLabel.text = md.name
            self.gameImageV.loadImage(url: md.icon)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        view.subviews{
            scrollView.subviews{
                containerView.subviews{
                    closeButton
                    gameImageV
                    titleLabel
                    sendButton
                    scoreLabel
                    starView
                    scoreSubLabel
                    lineView
                    textView
                    placeholderLabel
                    functionView
                    collectionView
                    picImageView
                }
            }
        }
        
        scrollView.backgroundColor = .clear
        containerView.backgroundColor = .clear
        scrollView.top(0).leading(0).width(.screenWidth).bottom(0)
        containerView.fillContainer().width(.screenWidth)
        closeButton.top(.statusHeight).leading(0).width(56.0.Scale).height(44.0.Scale)
        gameImageV.leading(56.0.Scale).size(24.0.Scale)
        gameImageV.CenterY == closeButton.CenterY
        titleLabel.Leading == gameImageV.Trailing + 8.0.Scale
        titleLabel.Trailing == sendButton.Leading - 8.0.Scale
        titleLabel.CenterY == closeButton.CenterY
        sendButton.trailing(0).top(.statusHeight).height(44.0.Scale).width(88.0.Scale)
        scoreLabel.leading(16.0.Scale).top(.navi_height + 15.0.Scale)
        starView.leading(56.0.Scale).top(.navi_height + 12.0.Scale).width(148.0.Scale).height(20.0.Scale)
        scoreSubLabel.Leading == starView.Trailing + 24.0.Scale
        scoreSubLabel.CenterY == starView.CenterY
        lineView.leading(16.0.Scale).trailing(16.0.Scale).height(1)
        lineView.Top == starView.Bottom + 20.0.Scale
        textView.leading(16.0.Scale).trailing(16.0.Scale).height(37.0.Scale)
        textView.Top == lineView.Bottom + 16.0.Scale
        placeholderLabel.leading(18.0.Scale).trailing(18.0.Scale)
        placeholderLabel.Top == lineView.Bottom + 18.0.Scale
        functionView.leading(16.0.Scale).trailing(0).height(33.0.Scale)
        functionView.Top == textView.Bottom + 12.0.Scale
        collectionView.leading(0).trailing(0).height(0).bottom(.tabBar_height)
        collectionView.Top == functionView.Bottom + 8.0.Scale
        picImageView.leading(16.0.Scale).trailing(16.0.Scale).height(195.0.Scale)
        picImageView.Top == textView.Bottom + 16.0.Scale
        
        sendButton.isEnabled = false
        textView.delegate = self
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        closeButton.addTarget(self, action: #selector(clickCloseButton), for: .touchUpInside)
        functionView.imgStr = ["Square_pushPic"]
        picImageView.isHidden = true
        
        functionView.functionButtonBlock = { funcID in
            self.checkPhotoLibraryPermission()
            self.textView.resignFirstResponder()
        }
        picImageView.delBlock = {
            self.functionView.isHidden = false
            self.picImageView.isHidden = true
        }
        
        starView.rating = 0
        starView.settings.starSize = 20.0.Scale
        starView.settings.starMargin = 12
        starView.settings.fillMode = .half
        starView.settings.emptyImage = "Common_emptyStar".toImage
        starView.settings.filledImage = "Common_fillStar".toImage

        starView.didFinishTouchingCosmos = {
            rating in
            self.point = Int(rating)*2
            if rating > 0 && rating <= 1{
                self.scoreSubLabel.text = "一星拿走"
            }else if rating > 1 && rating <= 2{
                self.scoreSubLabel.text = "夸不出口"
            }else if rating > 2 && rating <= 3{
                self.scoreSubLabel.text = "差点意思"
            }else if rating > 3 && rating < 5{
                self.scoreSubLabel.text = "入坑不亏"
            }else if rating == 5{
                self.scoreSubLabel.text = "按头推荐"
            }
            self.updateSendButtonState()
        }
        
        sendButton.addTarget(self, action: #selector(clickSendButton), for: .touchUpInside)
    }
    
    @objc private func clickCloseButton(){
        self.dismiss(animated: true)
    }
    
}

//MARK: Action
extension ClubGamesCommitViewController {
    
   private func checkPhotoLibraryPermission() {
        let status = PHPhotoLibrary.authorizationStatus()
            
        switch status {
            case .authorized:
                // 已经授权，继续访问相册
            DispatchQueue.main.async {
                self.showPhotoLibrary()
            }
                
            case .denied, .restricted:
                // 用户拒绝或受限，无法访问相册
                print("用户拒绝访问相册")
            case .notDetermined:
                // 用户还没有决定是否允许访问，进行请求
                PHPhotoLibrary.requestAuthorization { newStatus in
                    if newStatus == .authorized {
                        // 用户授权，继续访问相册
                        DispatchQueue.main.async {
                            self.showPhotoLibrary()
                        }
                    } else {
                        print("用户拒绝访问相册")
                    }
                }
        @unknown default:
                print("未知的权限状态")
        }
    }
    
    private func showPhotoLibrary() {

        let config = ZLPhotoConfiguration.default()
        
        config.languageType = .chineseSimplified
        config.maxSelectCount = 1
        config.allowSelectGif = false
        config.allowMixSelect = false
        config.allowSelectVideo = false
        config.allowTakePhotoInLibrary = true
        config.allowEditVideo = true
        config.maxEditVideoTime = 30
        config.maxRecordDuration = 30
        config.editAfterSelectThumbnailImage = true
        config.allowSelectOriginal = false
        config.animateSelectBtnWhenSelect = false
        config.cropVideoAfterSelectThumbnail = true
        let ac = ZLPhotoPreviewSheet(selectedAssets:nil)
        
        ac.selectImageBlock = { [weak self] (images, assets, isOriginal) in
            self?.images = images
            self?.assets = assets
            self?.loadImageData()
        }
        ac.showPhotoLibrary(sender: self)
    }
    
    @objc private func clickSendButton(){

        var contentText = textView.text ?? ""
        contentText = contentText.replacingOccurrences(of: "\n", with: "\r")
        if contentText.count <= 0 {
            "请输入评论内容".toast_error
            return
        }
        guard self.point > 0 else {
            "请选择评分".toast_error
            return
        }
        ToastUtil.show()
        if self.images.count > 0 {
            updateImage(content: contentText)
        }else{
            addDynamic(content: contentText, imgs: "", video: "")
        }

    }
    
    private func addDynamic(content: String, imgs: String, video: String){
        
        Task{
            
            let dict: [String: Any] = ["content": content, "images": imgs, "video": video, "id" : self.gameId, "point": self.point]
            let res = await self.network.requestSpecial(.commitGame(json: dict))
            if res.isSuccess {
                self.updateDataBlock?()
                self.dismiss(animated: true)
            }else{
                res.errorMessage?.toast_error
            }
            ToastUtil.dismiss()
        }
    }
    
    private func updateImage(content: String){
        self.imageUrlArr.removeAll()
        let upLoadImageGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "upLoadImageGroup")
        for i in 0..<images.count {
            upLoadImageGroup.enter()
            
            workingQueue.async {

                RaeRequestParameterConfig.shared.uploadImage(uploadImage: self.images[i]) { urlString in
                    self.imageUrlArr.append(urlString)
                    upLoadImageGroup.leave()
                } failure: { errorMessage in
                    upLoadImageGroup.leave()
                }
            }
        }
        upLoadImageGroup.notify(queue: workingQueue) {
            self.addDynamic(content: content, imgs: self.imageUrlArr.joined(separator: ","), video: "")
        }
    }
}

//MARK: TextView
extension ClubGamesCommitViewController: UITextViewDelegate {
    
    // UITextViewDelegate 方法
    func textViewDidChange(_ textView: UITextView) {
        // 计算文本内容的高度
        let size = CGSize(width: textView.frame.width, height: .infinity)
        let estimatedSize = textView.sizeThatFits(size)
        // 更新高度约束
        textView.heightConstraint?.constant = estimatedSize.height
        
        // 根据内容决定是否隐藏占位符
        placeholderLabel.isHidden = !textView.text.isEmpty
        self.updateSendButtonState()
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        // 开始编辑时隐藏占位符
        placeholderLabel.isHidden = true
    }
        
    func textViewDidEndEditing(_ textView: UITextView) {
        // 结束编辑时，如果内容为空，显示占位符
        if textView.text.isEmpty {
            placeholderLabel.isHidden = false
        }
    }
    
    private func updateSendButtonState(){
        if self.point > 0 && !textView.text.isEmpty && textView.text.count >= 8 {
            sendButton.isEnabled = true
        }else{
            sendButton.isEnabled = false
        }
    }
}


//MARK: data
extension ClubGamesCommitViewController {
    
    private func loadData(){
        
//        Task {
//            let models = await network.request(.dynamicTopic,type: ClubDynamicGameModel.self)
//            if models.isSuccess, let models = models.models {
//                var tempModels = [ClubDynamicGameModel]()
//                for var md in models {
//                    md.type = "1"
//                    tempModels.append(md)
//                }
//                self.topicModels = tempModels
//            }
//        }
        
//        Task {
//            let models = await network.request(.dynamicGame,type: ClubDynamicGameModel.self)
//            if models.isSuccess, let models = models.models {
//                var tempModels = [ClubDynamicGameModel]()
//                for var md in models {
//                    md.type = "2"
//                    tempModels.append(md)
//                }
//                self.gameModels = tempModels
//            }
//        }
    }
    
    private func loadImageData(){
        
        if self.images.count > 0 {
            self.functionView.isHidden = true
            self.picImageView.isHidden = false
            self.picImageView.imageView.image = self.images.first
        }else{
            self.functionView.isHidden = false
            self.picImageView.isHidden = true
        }
    }
}


//MARK:
class ClubGamesCommitMediaView: UIView {
    
    var imageView:UIImageView!
    let delButton = c_make_ex(UIButton.self)
        .image("GameDetail_del").end()
    private let shadowView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.1)).end()

    var delBlock: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        rae.corner(8)
        
        initUI()
        initFrame()
    }
    
    private func initUI() -> Void {

        // 可选：设置 contentView 的背景颜色以便于对比
        backgroundColor = UIColor.clear
        
        imageView = UIImageView.init()
        imageView.backgroundColor = UIColor.clear
        imageView.layer.masksToBounds = true
        imageView.contentMode = UIView.ContentMode.scaleAspectFill
        addSubview(imageView)
        
        imageView.addSubview(shadowView)
        
        delButton.addTarget(self, action: #selector(clickDelButton), for: .touchUpInside)
        addSubview(delButton)
    }
    
    private func initFrame() -> Void {
        
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        shadowView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        delButton.snp.makeConstraints { make in
            make.top.trailing.equalToSuperview()
            make.width.height.equalTo(40)
        }
    }
    
    @objc private func clickDelButton(){
        delBlock?()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
